package com.security.demo.service;

import com.security.demo.entity.Role;
import com.security.demo.entity.UserInfo;
import com.security.demo.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * UserDetailsService 为 Spring Security 系统类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    /**
     * 判断用户名和密码并设置角色
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo user = userMapper.getUserByName(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new UsernameNotFoundException("用户名或密码错误！");
        }
        List<Role> roleList = userMapper.getRoleListByUserId(user.getUserId());
        user.setRoles(roleList);
        return user;
    }
}
